
#include "Reg.h"

Reg::Reg( unsigned int baseAddress )
{
   RegMap( baseAddress );
}

Reg::~Reg()
{
   RegUnMap( );
}

void Reg::RegMap( unsigned int baseAddress )
{
   int fd;
   
   fd = open("/dev/mem", O_RDWR | O_SYNC);
   if (fd < 0)
   {
      printf("Cannot open /dev/mem. \n");
      exit(1);
   }
   
   m_MapAddress = mmap(0, 0x10000, PROT_READ | PROT_WRITE, MAP_SHARED, fd, (__off_t)baseAddress);
   
   if(m_MapAddress == (void *) -1)
   {
      printf("Can't map the 0x%x to the user space. \n", baseAddress);
   }
}

void Reg::RegUnMap()
{
   munmap(m_MapAddress, 0x10000);
}

void Reg::Write( unsigned int address, unsigned int data )
{
   //iowrite32( data, (unsigned int)m_MapAddress + address );
   *(volatile unsigned int *) ( (unsigned int)m_MapAddress + address * 0x4 ) = data;
}

unsigned int Reg::Read( unsigned int address )
{
   //return ioread32( (unsigned int)m_MapAddress + address );
   return *(volatile unsigned int *) ( (unsigned int)m_MapAddress + address * 0x4 );
}
